import requests
import json
import time
import random
import hashlib

# requests实现


def fanyi(content):
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    salt = str(int(round(time.time()*1000)) + random.randint(1, 10))
    sign = hashlib.md5(
        ("fanyideskweb" + content + salt + "p09@Bn{h02_BIEe]$P^nG").encode('utf-8')).hexdigest()

    # 定义请求参数
    data = {
        "i": content,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": salt,
        "sign": sign,
        "ts": "1546339944932",
        "bv": "363eb5a1de8cfbadd0cd78bd6bd43bee",
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_CLICKBUTTION",
        "typoResult": "false"
    }

    # 封装headers头信息
    headers = {
        'Accept': 'application/json, text/javascript, */*; q = 0.01',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN, zh; q = 0.9',
        'Connection': 'keep-alive',
        'Content-Length': str(len(data)),
        'Content-Type': 'application/x-www-form-urlencoded; charset = UTF-8',
        'Cookie': '''OUTFOX_SEARCH_USER_ID = -146090126@153.34.71.254; NTES_SESS = RGM0w0r5tuhBObabfJ6LzjMbCWel8p1lu7dxAXIoyqYwZhjsWZ8jzDwwpHS3MQaDjQuIyPOkDZS_V3vdjsnNy2m5ixzIkA72tFqmXtgAg4_k.olhIDSro10vTicufNtqApzwJobfgwaNkmOfLt0WU_fTDZoQUukeMsl5oQDM.BQ5fG3nvbpVNJX0p; ANTICSRF = 57e39a9329e9af7f7d0e89b2ea8f514c; S_INFO = 1545306834 | 0 | 3 & 40  # |a753090302; P_INFO=a753090302@163.com|1545306834|0|other|00&99|jis&1544447915&open#jis&320500#10#0#0|&0|open&study&open_client|a753090302@163.com; JSESSIONID=aaaMKSTDViEuCc1TsW_Fw; OUTFOX_SEARCH_USER_ID_NCOO=1791224776.7167377; ___rl__test__cookies=1546338897410''',
        'Host': 'fanyi.youdao.com',
        'Origin': 'http: // fanyi.youdao.com',
        'Referer': 'http: // fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }

    # 发送请求，抓取信息
    res = requests.post(url, data=data, headers=headers)

    # 解析结果并输出
    html = res.content.decode("utf-8")
    # 将JSON格式转换成字典类型
    translate = json.loads(html)
    translate_src = translate["translateResult"][0][0]["src"]
    translate_Result = translate["translateResult"][0][0]["tgt"]
    print("翻译内容：%s" % translate_src)
    print("翻译结果：%s" % translate_Result)


if __name__ == '__main__':
    while True:
        keyword = input('输入翻译的单词：')
        if keyword == 'q':
            break
        fanyi(keyword)
